<template>
  <uni-popup ref="popup" v-model="visible" type="center" :mask-click="false">
    <view class="modal-content">
      <view class="modal-header">
        <text class="modal-title">{{ getModalTitle() }}</text>
        <text class="modal-close" @click="closeModal">×</text>
      </view>
      <view class="form-container">
        <!-- 所属家族 -->
        <view class="form-item">
          <text class="form-label">所属家族</text>
          <picker
            :range="getActualOptions('familyOptions')"
            range-key="label"
            @change="handleFamilyChange"
          >
            <view class="picker">{{ getFamilyLabel(formData.familyId) }}</view>
          </picker>
        </view>

        <!-- 姓 -->
        <view class="form-item">
          <text class="form-label required">姓</text>
          <input v-model="formData.firstName" placeholder="请输入姓" class="form-input" />
        </view>

        <!-- 名 -->
        <view class="form-item">
          <text class="form-label required">名</text>
          <input v-model="formData.lastName" placeholder="请输入名" class="form-input" />
        </view>

        <!-- 昵称 -->
        <view class="form-item">
          <text class="form-label">昵称</text>
          <input v-model="formData.nickname" placeholder="请输入昵称" class="form-input" />
        </view>

        <!-- 字辈 -->
        <view class="form-item">
          <text class="form-label">字辈</text>
          <picker
            :range="getActualOptions('zibeiOptions')"
            range-key="label"
            @change="handleZibeiChange"
          >
            <view class="picker">{{ getZibeiLabel(formData.genation) }}</view>
          </picker>
        </view>

        <!-- 性别 -->
        <view class="form-item">
          <text class="form-label required">性别</text>
          <picker
            :range="getActualOptions('genderOptions')"
            range-key="label"
            @change="handleGenderChange"
          >
            <view class="picker">{{ getGenderLabel(formData.gender) }}</view>
          </picker>
        </view>

        <!-- 是否在世 -->
        <view class="form-item">
          <text class="form-label required">是否在世</text>
          <picker
            :range="getActualOptions('aliveOptions')"
            range-key="label"
            @change="handleAliveChange"
          >
            <view class="picker">{{ getAliveLabel(formData.alive) }}</view>
          </picker>
        </view>

        <!-- 头像照片 -->
        <view class="form-item">
          <text class="form-label required">头像照片</text>
          <AvatarUploader v-model="formData.photoUrl" />
        </view>

        <!-- 职业 -->
        <view class="form-item">
          <text class="form-label">职业</text>
          <input v-model="formData.occupation" placeholder="请输入职业" class="form-input" />
        </view>

        <!-- 籍贯 -->
        <view class="form-item">
          <text class="form-label required">籍贯</text>
          <input v-model="formData.birthPlace" placeholder="请输入籍贯" class="form-input" />
        </view>

        <!-- 地址 -->
        <view class="form-item">
          <text class="form-label required">地址</text>
          <input v-model="formData.address" placeholder="请输入地址" class="form-input" />
        </view>

        <!-- 经度 -->
        <view class="form-item">
          <text class="form-label">经度</text>
          <input v-model="formData.longitude" placeholder="请输入经度" class="form-input" />
        </view>

        <!-- 纬度 -->
        <view class="form-item">
          <text class="form-label">纬度</text>
          <input v-model="formData.latitude" placeholder="请输入纬度" class="form-input" />
        </view>

        <!-- 出生日期 -->
        <view class="form-item">
          <text class="form-label required">出生日期</text>
          <picker mode="date" @change="(e: any) => (formData.birthDate = e.detail.value)">
            <view class="picker">{{ formData.birthDate || "请选择出生日期" }}</view>
          </picker>
        </view>

        <!-- 死亡日期 -->
        <view class="form-item">
          <text class="form-label">死亡日期</text>
          <picker mode="date" @change="(e: any) => (formData.deathDate = e.detail.value)">
            <view class="picker">{{ formData.deathDate || "请选择死亡日期" }}</view>
          </picker>
        </view>

        <!-- 个人简介 -->
        <view class="form-item">
          <text class="form-label required">个人简介</text>
          <textarea
            v-model="formData.biography"
            placeholder="请输入个人简介"
            rows="3"
            class="form-textarea"
          />
        </view>

        <!-- 按钮 -->
        <view class="form-actions">
          <button class="submit-btn" @click="onSubmit">确定</button>
          <button class="cancel-btn" @click="closeModal">取消</button>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import AvatarUploader from "@/components/AvatarUploader/AvatarUploader.vue";

interface Option {
  label: string;
  value: string | number;
}

const props = defineProps<{
  familyOptions: Option[];
  zibeiOptions: Option[];
  genderOptions: Option[];
  aliveOptions: Option[];
  visible: boolean;
  operationType?: string; // 操作类型：'add-child', 'edit-info', 'add-spouse', 'add-parent'
  editData?: any; // 编辑时的初始数据
}>();

const emit = defineEmits<{
  close: [];
  submit: [data: any];
}>();

const visible = ref(props.visible);

// 默认选项数据
const defaultOptions = {
  familyOptions: [{ label: "请选择家族", value: "" }],
  zibeiOptions: [
    { label: "请选择字辈", value: "" },
    { label: "无字辈", value: "0" },
  ],
  genderOptions: [
    { label: "请选择性别", value: "" },
    { label: "男", value: "1" },
    { label: "女", value: "2" },
  ],
  aliveOptions: [
    { label: "请选择状态", value: "" },
    { label: "在世", value: "1" },
    { label: "已故", value: "0" },
  ],
};

const formData = ref({
  familyId: "",
  firstName: "",
  lastName: "",
  nickname: "",
  genation: "",
  gender: "",
  alive: "",
  photoUrl: "",
  occupation: "",
  birthPlace: "",
  address: "",
  longitude: "",
  latitude: "",
  birthDate: "",
  deathDate: "",
  biography: "",
});

// 获取实际选项数据，如果没有传入则使用默认值
const getActualOptions = (key: keyof typeof defaultOptions) => {
  const propOptions = props[key as keyof typeof props] as Option[];
  if (propOptions && propOptions.length > 0) {
    // 确保所有选项的值都是字符串类型，保持一致性
    return propOptions.map((option) => ({
      ...option,
      value: String(option.value),
    }));
  }
  return defaultOptions[key];
};

// 测试方法：打印所有选项数据
const logOptions = () => {
  console.log("=== 选择器选项数据 ===");
  console.log("原始props数据:");
  console.log("familyOptions:", props.familyOptions);
  console.log("zibeiOptions:", props.zibeiOptions);
  console.log("genderOptions:", props.genderOptions);
  console.log("aliveOptions:", props.aliveOptions);
  console.log("处理后的选项数据:");
  console.log("familyOptions:", getActualOptions("familyOptions"));
  console.log("zibeiOptions:", getActualOptions("zibeiOptions"));
  console.log("genderOptions:", getActualOptions("genderOptions"));
  console.log("aliveOptions:", getActualOptions("aliveOptions"));
  console.log("当前表单数据:", formData.value);
  console.log("=====================");
};

// 在组件挂载时打印选项数据
onMounted(() => {
  logOptions();
});

// 监听编辑数据变化，预填充表单
watch(
  () => props.editData,
  (newData) => {
    console.log("addChildPop.vue editData变化:", newData, props.operationType);
    if (newData && props.operationType === "edit-info") {
      // 预填充表单数据，确保所有值都是字符串类型
      formData.value = {
        familyId: String(newData.familyId || ""),
        firstName: newData.firstName || "",
        lastName: newData.lastName || "",
        nickname: newData.remark || newData.nickname || "",
        genation: String(newData.genation || ""),
        gender: String(newData.gender || ""),
        alive: String(newData.alive || ""),
        photoUrl: newData.photoUrl || "",
        occupation: newData.occupation || "",
        birthPlace: newData.birthPlace || "",
        address: newData.address || "",
        longitude: newData.longitude || "",
        latitude: newData.latitude || "",
        birthDate: newData.birthDate || "",
        deathDate: newData.deathDate || "",
        biography: newData.biography || "",
      };
      console.log("addChildPop.vue 表单数据已更新:", formData.value);
    } else {
      // 重置表单数据
      formData.value = {
        familyId: "",
        firstName: "",
        lastName: "",
        nickname: "",
        genation: "",
        gender: "",
        alive: "",
        photoUrl: "",
        occupation: "",
        birthPlace: "",
        address: "",
        longitude: "",
        latitude: "",
        birthDate: "",
        deathDate: "",
        biography: "",
      };
      console.log("addChildPop.vue 表单数据已重置");
    }
  },
  { immediate: true }
);

// 监听visible变化，确保弹窗显示时数据正确
watch(
  () => props.visible,
  (val) => {
    console.log("addChildPop.vue visible变化:", val);
    visible.value = val;

    // 当弹窗显示时，确保编辑数据正确赋值
    if (val && props.editData && props.operationType === "edit-info") {
      console.log("addChildPop.vue 弹窗显示，重新赋值编辑数据:", props.editData);
      formData.value = {
        familyId: String(props.editData.familyId || ""),
        firstName: props.editData.firstName || "",
        lastName: props.editData.lastName || "",
        nickname: props.editData.remark || props.editData.nickname || "",
        genation: String(props.editData.genation || ""),
        gender: String(props.editData.gender || ""),
        alive: String(props.editData.alive || ""),
        photoUrl: props.editData.photoUrl || "",
        occupation: props.editData.occupation || "",
        birthPlace: props.editData.birthPlace || "",
        address: props.editData.address || "",
        longitude: props.editData.longitude || "",
        latitude: props.editData.latitude || "",
        birthDate: props.editData.birthDate || "",
        deathDate: props.editData.deathDate || "",
        biography: props.editData.biography || "",
      };
    }
  }
);

function getFamilyLabel(val: string | number): string {
  const options = getActualOptions("familyOptions");
  const result = options.find((i: Option) => String(i.value) === String(val))?.label || "请选择";
  console.log("getFamilyLabel:", val, "结果:", result, "选项:", options);
  return result;
}

function getZibeiLabel(val: string | number): string {
  const options = getActualOptions("zibeiOptions");
  const result = options.find((i: Option) => String(i.value) === String(val))?.label || "请选择";
  console.log("getZibeiLabel:", val, "结果:", result, "选项:", options);
  return result;
}

function getGenderLabel(val: string | number): string {
  const options = getActualOptions("genderOptions");
  const result = options.find((i: Option) => String(i.value) === String(val))?.label || "请选择";
  console.log("getGenderLabel:", val, "结果:", result, "选项:", options);
  return result;
}

function getAliveLabel(val: string | number): string {
  const options = getActualOptions("aliveOptions");
  const result = options.find((i: Option) => String(i.value) === String(val))?.label || "请选择";
  console.log("getAliveLabel:", val, "结果:", result, "选项:", options);
  return result;
}

function handleFamilyChange(e: any) {
  const selectedIndex = e.detail.value;
  const options = getActualOptions("familyOptions");
  const selectedOption = options[selectedIndex];
  console.log("选择家族:", selectedOption, "索引:", selectedIndex);
  formData.value.familyId = String(selectedOption.value);
  console.log("更新后的familyId:", formData.value.familyId);
}

function handleZibeiChange(e: any) {
  const selectedIndex = e.detail.value;
  const options = getActualOptions("zibeiOptions");
  const selectedOption = options[selectedIndex];
  console.log("选择字辈:", selectedOption, "索引:", selectedIndex);
  formData.value.genation = String(selectedOption.value);
  console.log("更新后的genation:", formData.value.genation);
}

function handleGenderChange(e: any) {
  const selectedIndex = e.detail.value;
  const options = getActualOptions("genderOptions");
  const selectedOption = options[selectedIndex];
  console.log("选择性别:", selectedOption, "索引:", selectedIndex);
  formData.value.gender = String(selectedOption.value);
  console.log("更新后的gender:", formData.value.gender);
}

function handleAliveChange(e: any) {
  const selectedIndex = e.detail.value;
  const options = getActualOptions("aliveOptions");
  const selectedOption = options[selectedIndex];
  console.log("选择是否在世:", selectedOption, "索引:", selectedIndex);
  formData.value.alive = String(selectedOption.value);
  console.log("更新后的alive:", formData.value.alive);
}

function onSubmit() {
  // 验证必填字段
  if (!formData.value.firstName || !formData.value.lastName) {
    uni.showToast({
      title: "请填写姓名",
      icon: "none",
    });
    return;
  }

  // 验证性别
  if (!formData.value.gender) {
    uni.showToast({
      title: "请选择性别",
      icon: "none",
    });
    return;
  }

  // 验证是否在世
  if (!formData.value.alive) {
    uni.showToast({
      title: "请选择是否在世",
      icon: "none",
    });
    return;
  }

  // 验证头像照片
  if (!formData.value.photoUrl) {
    uni.showToast({
      title: "请上传头像照片",
      icon: "none",
    });
    return;
  }

  // 验证籍贯
  if (!formData.value.birthPlace) {
    uni.showToast({
      title: "请填写籍贯",
      icon: "none",
    });
    return;
  }

  // 验证地址
  if (!formData.value.address) {
    uni.showToast({
      title: "请填写地址",
      icon: "none",
    });
    return;
  }

  // 验证出生日期
  if (!formData.value.birthDate) {
    uni.showToast({
      title: "请选择出生日期",
      icon: "none",
    });
    return;
  }

  // 验证死亡日期（如果选择已故）
  if (formData.value.alive === "0" && !formData.value.deathDate) {
    uni.showToast({
      title: "已故人员请填写死亡日期",
      icon: "none",
    });
    return;
  }

  // 验证个人简介
  if (!formData.value.biography) {
    uni.showToast({
      title: "请填写个人简介",
      icon: "none",
    });
    return;
  }

  // 验证姓名长度
  if (formData.value.firstName.length > 10 || formData.value.lastName.length > 10) {
    uni.showToast({
      title: "姓名长度不能超过10个字符",
      icon: "none",
    });
    return;
  }

  // 验证昵称长度
  if (formData.value.nickname && formData.value.nickname.length > 20) {
    uni.showToast({
      title: "昵称长度不能超过20个字符",
      icon: "none",
    });
    return;
  }

  // 验证职业长度
  if (formData.value.occupation && formData.value.occupation.length > 50) {
    uni.showToast({
      title: "职业长度不能超过50个字符",
      icon: "none",
    });
    return;
  }

  // 验证籍贯长度
  if (formData.value.birthPlace.length > 100) {
    uni.showToast({
      title: "籍贯长度不能超过100个字符",
      icon: "none",
    });
    return;
  }

  // 验证地址长度
  if (formData.value.address.length > 200) {
    uni.showToast({
      title: "地址长度不能超过200个字符",
      icon: "none",
    });
    return;
  }

  // 验证经度格式
  if (formData.value.longitude) {
    const longitude = parseFloat(formData.value.longitude);
    if (isNaN(longitude) || longitude < -180 || longitude > 180) {
      uni.showToast({
        title: "经度格式不正确，范围应在-180到180之间",
        icon: "none",
      });
      return;
    }
  }

  // 验证纬度格式
  if (formData.value.latitude) {
    const latitude = parseFloat(formData.value.latitude);
    if (isNaN(latitude) || latitude < -90 || latitude > 90) {
      uni.showToast({
        title: "纬度格式不正确，范围应在-90到90之间",
        icon: "none",
      });
      return;
    }
  }

  // 验证出生日期不能晚于当前日期
  const birthDate = new Date(formData.value.birthDate);
  const currentDate = new Date();
  if (birthDate > currentDate) {
    uni.showToast({
      title: "出生日期不能晚于当前日期",
      icon: "none",
    });
    return;
  }

  // 验证死亡日期不能早于出生日期
  if (formData.value.deathDate) {
    const deathDate = new Date(formData.value.deathDate);
    if (deathDate < birthDate) {
      uni.showToast({
        title: "死亡日期不能早于出生日期",
        icon: "none",
      });
      return;
    }
  }

  // 验证个人简介长度
  if (formData.value.biography.length > 500) {
    uni.showToast({
      title: "个人简介长度不能超过500个字符",
      icon: "none",
    });
    return;
  }

  // 验证特殊字符
  const specialCharRegex = /[<>\"'&]/;
  if (
    specialCharRegex.test(formData.value.firstName) ||
    specialCharRegex.test(formData.value.lastName) ||
    (formData.value.nickname && specialCharRegex.test(formData.value.nickname))
  ) {
    uni.showToast({
      title: "姓名和昵称不能包含特殊字符",
      icon: "none",
    });
    return;
  }

  // 提交数据
  emit("submit", { ...formData.value });
}

function closeModal() {
  emit("close");
}

function getModalTitle(): string {
  if (props.operationType === "add-child") {
    return "添加子辈";
  } else if (props.operationType === "edit-info") {
    return "编辑信息";
  } else if (props.operationType === "add-spouse") {
    return "添加配偶";
  } else if (props.operationType === "add-parent") {
    return "添加长辈";
  }
  return "添加子辈"; // 默认标题
}

function testSelectFamily() {
  console.log("测试选择家族");
  const options = getActualOptions("familyOptions");
  if (options.length > 0) {
    uni.showActionSheet({
      title: "请选择家族",
      itemList: options.map((opt) => opt.label),
      success: (res) => {
        if (res.tapIndex !== -1) {
          const selectedOption = options[res.tapIndex];
          console.log("选择家族:", selectedOption, "索引:", res.tapIndex);
          formData.value.familyId = String(selectedOption.value);
          console.log("更新后的familyId:", formData.value.familyId);
        }
      },
      fail: (err) => {
        console.error("选择家族失败:", err);
      },
    });
  } else {
    uni.showToast({
      title: "家族选项为空",
      icon: "none",
    });
  }
}

function testSelectGender() {
  console.log("测试选择性别");
  const options = getActualOptions("genderOptions");
  if (options.length > 0) {
    uni.showActionSheet({
      title: "请选择性别",
      itemList: options.map((opt) => opt.label),
      success: (res) => {
        if (res.tapIndex !== -1) {
          const selectedOption = options[res.tapIndex];
          console.log("选择性别:", selectedOption, "索引:", res.tapIndex);
          formData.value.gender = String(selectedOption.value);
          console.log("更新后的gender:", formData.value.gender);
        }
      },
      fail: (err) => {
        console.error("选择性别失败:", err);
      },
    });
  } else {
    uni.showToast({
      title: "性别选项为空",
      icon: "none",
    });
  }
}

function testSelectAlive() {
  console.log("测试选择状态");
  const options = getActualOptions("aliveOptions");
  if (options.length > 0) {
    uni.showActionSheet({
      title: "请选择状态",
      itemList: options.map((opt) => opt.label),
      success: (res) => {
        if (res.tapIndex !== -1) {
          const selectedOption = options[res.tapIndex];
          console.log("选择状态:", selectedOption, "索引:", res.tapIndex);
          formData.value.alive = String(selectedOption.value);
          console.log("更新后的alive:", formData.value.alive);
        }
      },
      fail: (err) => {
        console.error("选择状态失败:", err);
      },
    });
  } else {
    uni.showToast({
      title: "状态选项为空",
      icon: "none",
    });
  }
}
</script>

<style scoped>
.modal-content {
  background: #fff;
  padding: 28px 18px 18px 18px;
  border-radius: 16px;
  box-shadow: 0 2px 16px #eee;
  max-width: 90vw;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f2f2f2;
}

.modal-title {
  font-size: 20px;
  font-weight: 600;
  color: #222;
}

.modal-close {
  font-size: 28px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.modal-close:hover {
  background-color: #f8f9fa;
  color: #dc3545;
  transform: scale(1.1);
}

.form-container {
  padding: 0;
}

.form-item {
  margin-bottom: 18px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f2f2f2;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-label {
  font-weight: 600;
  font-size: 16px;
  color: #222;
  margin-bottom: 2px;
  display: block;
}

.form-label.required::before {
  content: "* ";
  color: #ff4d4f;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  font-size: 15px;
  color: #333;
  background: #fafbfc;
  transition: border 0.2s;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus {
  border: 1.5px solid #165dff;
  background: #fff;
}

.form-textarea {
  min-height: 80px;
  resize: vertical;
  font-family: inherit;
}

.picker {
  padding: 8px 10px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  font-size: 15px;
  color: #666;
  background: #fafbfc;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.picker:hover {
  border-color: #165dff;
  background-color: #fff;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 28px;
}

.submit-btn,
.cancel-btn {
  flex: 1;
  height: 42px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 600;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn {
  background: #3c9cff;
  color: #fff;
}

.submit-btn:hover {
  background: #2d8cf0;
  transform: translateY(-1px);
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #e8e8e8;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-content {
    padding: 16px;
    margin: 16px;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .submit-btn,
  .cancel-btn {
    width: 100%;
  }
}

/* 滚动条样式 */
.modal-content::-webkit-scrollbar {
  width: 6px;
}

.modal-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.modal-content::-webkit-scrollbar-thumb {
  background: #3c9cff;
  border-radius: 3px;
}

.modal-content::-webkit-scrollbar-thumb:hover {
  background: #2d8cf0;
}

/* 输入框占位符样式 */
.form-input::placeholder,
.form-textarea::placeholder {
  color: #bbb;
  font-size: 14px;
}
.form-input {
  height: 38px;
}

/* 调试信息样式 */
.debug-info {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
  font-size: 12px;
  color: #666;
}

.debug-info text {
  display: block;
  margin-bottom: 4px;
  font-family: monospace;
}

.test-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.test-btn {
  flex: 1;
  height: 30px;
  border-radius: 15px;
  font-size: 13px;
  font-weight: 600;
  border: 1px solid #e5e6eb;
  background: #fff;
  color: #333;
  cursor: pointer;
  transition: all 0.2s ease;
}

.test-btn:hover {
  background: #f0f0f0;
  border-color: #165dff;
  color: #165dff;
}
</style>
